<?php


namespace app\common\helper;

use Httpful\Request as rq;

class DingTalk
{
    /**
     * @var string 钉钉发送通知类，链式操作
     * 支持发送 Text MarkDown 成功发送返回code 1
     * 后台设置推送地址 和 密码
     */
    protected $uri ;
    protected $access_token ;
    protected $sendData; // 发送的数据
    protected $sendUrl; // 拼装完成后的URL

    public function __construct()
    {
        $config = cache("Config");
        $this->access_token = $config["ding_key"];
        $this->uri = $config["ding_url"];
    }


    protected function makeSignUrl()
    {
        $timestamp = time() * 1000;
        $signStr = $timestamp . "\n" . $this->access_token;
        $sign = hash_hmac('sha256', $signStr, $this->access_token, true);
        $sign = base64_encode($sign);
        $sign = urlencode($sign);
        $this->sendUrl = $this->uri . "&timestamp=" . $timestamp . "&sign=" . $sign;
    }

    public function sendText($text)
    {
        $sendData = [
            "msgtype" => "text",
            "text" => [
                "content" => $text
            ]
        ];
        $this->sendData = $sendData;
        return $this;
    }

    public function sendMarkDown($title, $text)
    {
        $sendData = [
            "msgtype" => "markdown",
            "markdown" => [
                "title" => $title,
                "text" => $text
            ]
        ];
        $this->sendData = $sendData;
        return $this;
    }

    public function send()
    {
        $this->makeSignUrl();
        $result = rq::post($this->sendUrl)
            ->body(json_encode($this->sendData))
            ->sendsJson()
            ->send();
        if ($result->body->errcode == 0) {
            $data = [
                "code" => 1,
                "msg"  => "推送成功"
            ];
        } else {
            $data = [
                "code" => $result->body->errcode,
                "msg"  => $result->body->errmsg
            ];
        }
        return $data;
    }
}